<template>
  <el-form ref="form" :model="form" inline="true" label-width="120px">

    <div style="padding-left:20px;padding-top:10px;text-align:left;" v-if="this.StepSN==0">

      <el-button type="primary" icon="el-icon-tickets" size="mini" @click="confirmData(4)">保存</el-button>
      <el-button type="primary" icon="el-icon-check" size="mini" @click="confirmData(2)">提交</el-button>
      <el-button type="success" icon="el-icon-download" size="mini" @click="handlexportData">导出</el-button>
      <!--  <el-button type="primary" @click="calculation" size="mini" icon="el-icon-thumb">计算费用</el-button>
      <el-button type="primary" @click="checkWork" size="mini" icon="el-icon-date">获取考勤</el-button>
      <el-button type="primary" @click="getPeople" size="mini" icon="el-icon-search">获取数据</el-button>
 -->
    </div>

    <div style="padding-left:20px;padding-top:10px;text-align:left;" v-if="this.StepSN>0">
      <!-- <el-button type="primary" icon="el-icon-tickets" size="mini" @click="confirmData(4)">保存</el-button> -->
      <el-button type="primary" icon="el-icon-check" size="mini" @click="confirmData(3)">退回上一步</el-button>
      <el-button type="primary" icon="el-icon-check" size="mini" @click="confirmData(2)">审核</el-button>
      <el-button type="success" icon="el-icon-download" size="mini" @click="handlexportData">导出</el-button>
    </div>
    <el-card class="box-card" style="padding-left:20px;padding-top: 10px;">
      <div slot="header" class="clearfix">
        <span>
          车费信息
        </span>
      </div>
      <div v-for="o in 1" :key="o" class="text item">
        <table style="width:100%">
          <tr>
            <td>
              <el-form-item label="车费单号：">
                <el-input v-model="form.TemporaryfareCostNo" disabled></el-input>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="单位名称：">
                <el-select v-model="form.Organizeid" clearable placeholder="单位" style="width: 100%; display: flex;"
                  @change="selectChange">
                  <el-option v-for="item in OrganizeList" :key="item.Organizeid" :label="item.Organizename" :value="item.Organizeid">
                  </el-option>
                </el-select>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="输送机构：">
                <el-select v-model="form.Conveyingmechanism" clearable placeholder="机构" style="width: 100%; display: flex;">
                  <el-option v-for="item in Conveyingmechanismlist" :key="item.Conveyingmechanism" :label="item.Conveyingmechanism"
                    :value="item.Conveyingmechanism">
                  </el-option>
                </el-select>
              </el-form-item>
            </td>
            <td>
              <el-form-item label="发放月份：">
                <el-date-picker v-model="form.SendMonth" type="month" value-format="yyyy-MM" placeholder="选择月" @change="getCenter">
                </el-date-picker>
              </el-form-item>
            </td>
          </tr>
        </table>
      </div>
    </el-card>
    <el-card class="box-card" style="padding-left:20px;padding-top: 10px;">
      <div slot="header" class="clearfix">
        <span>
          车费明细
        </span>

        <el-button style="float: right; padding: 3px 0" @click="addRow(1)" type="success" icon="el-icon-plus">添加一行</el-button>
      </div>
      <div v-for="o in 1" :key="o" class="text item">

        <el-table v-loading="loading" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)" :data="formDetail" :height="tableHeight" style="width: 100%;margin-top: 0px;"
          border show-summary :summary-method="getTotal">

          <el-table-column type="index" width="50" label="序号" fixed>
          </el-table-column>



          <el-table-column align="center" label="单位" width="150px" fixed>
            <template slot-scope="scope">
              <el-input v-model="scope.row.Organizename"></el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="工号" width="150px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.UserCode"></el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="姓名" width="100px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.UserName"></el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="性别">
            <template slot-scope="scope">
              <el-select v-model="scope.row.Sex" placeholder="请选择">
                <el-option v-for="item in SexOption" :key="item.value" :label="item.label" :value="item.value">
                  <span style="float: left">{{ item.label }}</span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>

          <el-table-column align="center" label="职位" width="100px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.JobName"></el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="职级">
            <template slot-scope="scope">
              <el-input v-model="scope.row.JobLevel"></el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="聘用日期" width="150px">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.JoinedDate" type="date" placeholder="选择日期">
              </el-date-picker>
            </template>
          </el-table-column>

          <el-table-column align="center" label="离职日期" width="150px">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.DimissionDate" type="date" placeholder="选择日期">
              </el-date-picker>
            </template>
          </el-table-column>
          <el-table-column align="center" label="出勤情况" width="100px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.AttendanceDay"></el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="输送机构" width="150px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.Conveyingmechanism"></el-input>
              <!-- <el-select v-model="scope.row.Conveyingmechanism" clearable placeholder="机构" style="width: 100%; display: flex;">
                <el-option v-for="item in Conveyingmechanismlist" :key="item.Conveyingmechanism" :label="item.Conveyingmechanism"
                  :value="item.Conveyingmechanism">
                </el-option>
              </el-select> -->
            </template>
          </el-table-column>

          <el-table-column align="center" label="输送期限" width="150px">
            <template slot-scope="scope">
              <el-date-picker v-model="scope.row.EndConveyorDate" type="date" placeholder="选择日期">
              </el-date-picker>
            </template>
          </el-table-column>

          <el-table-column align="center" label="考勤记录" width="150px">
            <template slot-scope="scope">
              <el-input v-model="scope.row.CardRecord"></el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="车费补贴" width="100px" prop="Cost">
            <template slot-scope="scope">
              <el-input v-model="scope.row.Cost"></el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" circle size="small" @click="delData(scope)"></el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <div style="float: right;  padding-top: 10px">
          <el-pagination background layout="sizes, prev, pager, next,total" :page-size="Search.pageSize" :total="Search.total"
            @current-change="pageChange" />
        </div> -->
      </div>
    </el-card>
    <el-card class="box-card" style="padding-left: 20px; padding-top: 10px">
      <div class="block">
        <div class="radio">
          工作流：
        </div>

        <el-timeline :reverse="true" ref="ListLog" :model="ListLog">
          <el-timeline-item v-for="(activity, index) in ListLog" :key="index" :timestamp="activity.CreateDateTime">
            {{ activity.Remark }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </el-form>
</template>
<style>
  .customWidth {
    width: 80%;
    height: 500px
  }
</style>

<script>
  import path from 'path'
  import {
    deepClone
  } from '@/utils'
  import {
    funDownload
  } from '@/api/Common'
  import {
    getDataList,
    deleteBody,
    updateCarFareBody,
    updateAttendanceCar,
    getWorkerByOrganize,
    deleteDetail,
    getCarCenter,
    setCarCostIsEnd
  } from '@/api/school'
  import {
    calculateCarCost
  } from '@/api/enterprise'
  import elementIcons from '../icons/element-icons'
  import {
    getSelectList
  } from '@/api/getSelect'

  export default {

    components: {
      //   vProjectBillOpen
    },

    props: {
      inputName: String,
      required: true
    },
    data() {
      return {
        activeName: 'first',
        disabledStatus: false,
        loading: false,
        form: {},
        formDetail: [],
        selectlist: [],
        selectDepList: [],
        StepSN: -1,
        ListLog: [],
        OrganizeList: [],
        Conveyingmechanismlist: [],
        SexOption: [{
          value: '2',
          label: '男'
        }, {
          value: '1',
          label: '女'
        }],
        Search: { // 查询条件
          total: 0, // 总记录数
          pageSize: 10, // 一页显示的记录数
          page: 1, // /当前页码
          RNO: '005', // 表编号  根据Controller中对应的表编号
          jsWhere: '' // 自定义条件
        },
        SearchHead: { // 查询条件
          RNO: '004', // 表编号  根据Controller中对应的表编号
          jsWhere: '' // 自定义条件
        },
        SearchSelect: { // 查询条件
          total: 0, // 总记录数
          RNO: '001', // 表编号  根据Controller中对应的表编号
          jsWhere: '' // 自定义条件
        },
        SearchApproval: { // 查部门
          total: 0, // 总记录数
          pageSize: 100, // 一页显示的记录数
          RNO: '002', // 表编号  根据Controller中对应的表编号
          jsWhere: '' // 自定义条件
        },
        multipleTable: [],
        dialogTableVisible: false,
        dialogFormVisible: false,
        where: "",
      }
    },
    created: function() {
      this.getSelect()
      this.DataListData();
      if (this.$route.query.billID != undefined) {
        this.disabledStatus = true;
      }
    },

    methods: {
      pageChange(page) { // 翻页
        this.Search.page = page
        this.DataListData()
      },
      handlexportData() {
        funDownload("1545", JSON.stringify(this.Search))
      },
      async DataListData() { // 获取数据
        if (this.$route.query.billID != undefined) {
          //获取表单头
         /* this.SearchHead.TemporaryfareCostNo = this.$route.query.billID
          const resultHead = await getDataList({
            data: JSON.stringify(this.SearchHead)
          })
          this.Search.TemporaryCostNo = this.$route.query.billID
          const resultBody = await getDataList({
            data: JSON.stringify(this.Search)
          })
          if (this.inputName == null) {
            this.inputName = this.$route.query.billID;
          }
          this.form = resultHead.data.Table[0];
          this.formDetail = resultBody.data.Table;
          this.Search.total = resultBody.data.Table1[0].RecordCount */
          const result = await updateCarFareBody({
            billID: this.$route.query.billID,
            IsPostBack: false,
          });
          this.form = result.data1.Table[0];
          this.formDetail = result.data2.Table;
          this.selectlist = result.data3.Table;
          this.ListLog = result.ListLog;
          this.StepSN = result.StepSN;
        } else {
          this.StepSN = 0;
        }


      },
      async confirmData(submit) { // 提交数据，需要修改

        const Fresult = true;
        //点击提交
        if (submit == 2) {

          this.$refs["form"].validate((valid) => {
            if (!valid) {
              this.$notify({
                title: "不能提交",
                dangerouslyUseHTMLString: true,
                message: "不可为空，不能提交",
                type: "error"
              });
              Fresult = false;
              return false;
            }
          });
        }
        if (submit == 4) {
          this.loading = true
          this.form.DeliverType = 2
          const result = await updateCarFareBody({
            BodyDate: JSON.stringify(this.formDetail),
            HeadDate: JSON.stringify(this.form),
            billID: this.$route.query.billID,
            IsPostBack: true,
            submit: 0,
          });
          this.form = result.data1.Table[0];
          this.formDetail = result.data2.Table;
          this.selectlist = result.data3.Table;
          this.ListLog = result.ListLog;
          this.StepSN = result.StepSN;
          if (result.code === 20000) {
            this.DataListData()
            this.loading = false
            this.$message({
              message: '保存成功',
              type: 'success'
            });
          } else {
            this.$notify({
              title: 'error',
              dangerouslyUseHTMLString: true,
              message: result.message,
              type: 'error'
            })
          }
          Fresult = false;
        }
        //点击保存
        if (Fresult) {
          this.loading = true
          this.form.DeliverType = 2
          const result = await updateCarFareBody({
            BodyDate: JSON.stringify(this.formDetail),
            HeadDate: JSON.stringify(this.form),
            billID: this.form.TemporaryfareCostNo,
            IsPostBack: true,
            submit: submit,
            Organizeid: this.form.Organizeid,
            DeliverType: 2,
          });
           loading.close();
          this.form = result.data1.Table[0];
          this.formDetail = result.data2.Table;
          this.selectlist = result.data3.Table;
          this.ListLog = result.ListLog;
          this.StepSN = result.StepSN;
          if (result.code === 20000) {
            this.DataListData()
            this.loading = false
            this.$message({
              message: '保存成功',
              type: 'success'
            });
            if (submit != 2) {
              this.checkWork()
            }

          } else {
            this.$notify({
              title: 'error',
              dangerouslyUseHTMLString: true,
              message: result.message,
              type: 'error'
            })
          }
        }

        if (this.StepSN == -1) {
          const ressss = await setCarCostIsEnd({
            ID: this.form.TemporaryfareCostNo
          })
        }

        if (submit == 3) {

        }

      },
      //删除表身内容
      async DeleteDetail() {
        this.loading = true
        const result = await deleteDetail({
          billID: this.$route.query.billID,
          dataBase: "TLC_TemporaryfareCostDetail",
          name: "TemporaryCostNo"
        })
        if (result.code === 20000) {
          this.DataListData()
          this.loading = false
        }
      },
      //根据公司获取员工
      async getPeople() {
        if (this.formDetail.length != 0) {
          this.DeleteDetail()
        }
        const res3 = await getWorkerByOrganize({
          billID: this.form.Organizeid,
          UserType: 2
        })
        this.formDetail = res3.data.Table;
        this.confirmData(0);
      },
      //计算费用
      async calculation() {
        this.loading = true
        if (this.$route.query.billID == null) {
          this.$route.query.billID = this.form.TemporaryfareCostNo
        }
        const result = await calculateCarCost({
          billID: this.$route.query.billID
        })
        if (result.code === 20000) {
          this.DataListData()
          this.loading = false
        }
      },
      //获取考勤
      async checkWork() {
        if (this.form.SendMonth == null || this.form.SendMonth == "") {
          this.$message({
            message: '发放月份不能为空',
            type: 'warning'
          });
        } else {
          this.loading = true
          if (this.$route.query.billID == null) {
            this.$route.query.billID = this.form.TemporaryfareCostNo
          }
          const result = await updateAttendanceCar({
            billID: this.$route.query.billID,
            sendDate: this.form.SendMonth
          })
          if (result.code === 20000) {
            this.DataListData()
            this.loading = false
          }
          this.calculation()
        }

      },
      async getSelect() { // 获取下拉

        const res2 = await getSelectList({
          data: JSON.stringify(this.SearchApproval)
        })
        this.OrganizeList = res2.data.Table
      },
      async getConvey(){
        this.SearchSelect.Organizeid = this.form.Organizeid
        const res = await getDataList({
          data: JSON.stringify(this.SearchSelect)
        })
        this.Conveyingmechanismlist = res.data.Table
      },
      //下拉选择单位的时候 单位名称跟随单位修改
      selectChange(val) {

        let obj = {};
        obj = this.OrganizeList.find((item) => {
          return item.Organizeid === val;
        });
        this.form.Organizename = obj.Organizename
        this.getConvey()
      },
      // 删除方法 选中行
      delData({
        $index,
        row
      }) {
        if (row.ID != undefined) {
          this.$confirm('确定删除序号为 ' + row.ID + ' 的数据吗?', {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            await deleteBody({
              ID: JSON.stringify(row.ID),
              status: "car"
            })
            this.formDetail.splice($index, 1)
          })
        } else {
          this.formDetail.splice($index, 1);
        }
      },
      getTotal(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = "合计";
            return;
          }
          const values = data.map((item) => Number(item[column.property]));
          if (index === 13) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index];
          } else {
            sums[index] = "--";
          }
        });

        return sums;
      },
      //增加行
      addRow(types) {
        let list = {

        };
        if (types == 1) {
          this.formDetail.push(list);
        }
      },
      async getCenter() {
        if (this.form.SendMonth != '' && this.form.SendMonth != null && this.form.Organizeid != '' && this.form.Organizeid !=
          null) {
          this.loading = true
          const res3 = await getCarCenter({
            SendMonth: this.form.SendMonth,
            Organizeid: this.form.Organizeid,
            DeliverType: 2,
            IsEnd: 1
          })
          this.formDetail = res3.data.Table
          this.loading = false
        }
      },
      select_status(val) {
        this.$forceUpdate();
      }
    }
  }
</script>
